
//上传文件
function uploadFile(name,v) {
    layer.load();
    // let oldLen = this.filLen;
    let sql='app.file = app.$refs.'+name+'.files[0]';
    eval(sql);
    let len = _this.file.length;
    let size = Math.floor(_this.file.size / 1024);
    if (size > 20 * 1024 * 1024) {
        alert("请选择20M以内的图片！");
        return false;
    }

    let formData= new FormData();
    formData.append('file',_this.file);
    PostFileUrl("/api/bc.Uploads",formData,function(e) {
        if(e.code==0){
            let sql='app.'+v+' = e.filepath';
            eval(sql);
            console.log('上传图片完成 ');
            layer.msg('上传完成');
            setTimeout(function () {
                layer.closeAll();
            },1000);


        }else{
            alert(e.msg);
        }
        //formData=new FormData();
    });

}

/**
 * @return 时间格式化
 * @param times 原时间
 * @param formats 要格式化的格式YYYY/MM/DD
 */
function timeToFormat(times,formats){
    //依赖：    <script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    if(formats==''){formats='YYYY/MM/DD';}
    if(times){
        return moment(times).format(formats);
    }else{
        return '';
    }
}

/**
 *
 * @return 根据SORT长度返回前置占位符
 * @param e item.cxSort
 */
function sortl(e){
    let s;
    s='';
    if(e){
        if(e.length==10){s='├--';}
        if(e.length==15){s='├----';}
        if(e.length==20){s='├-------';}
        if(e.length==25){s='├-----------';}
    }
    return s;
}

/**
 * @return OBJECT里获取对应标题里的值
 * @param mdata 完整字符串
 * @param n 要取值的对象
 */
function  getAtt(mdata,n){
    if(mdata!=undefined && mdata!=''){
        let s=JSON.parse(mdata);
        for(var i=0;i<s.length;i++){
            if(s[i].title==n){
                return s[i].content;
                break;
            }
        }
    }else{
        return '';
    }
}

function CheckToken(callback){
    if(getQV('code')){
        PostUrl('/api/v2.Wechat/weChatBackData',{code:getQV('code')},function(e){
            layer.msg('登陆成功');
            localStorage.id=e.data.cxid;
            localStorage.username=e.data.cxusername;
            localStorage.token=e.data.cxtoken;
            localStorage.level=e.data.cxuserlevel;
            localStorage.img=e.data.cximg0;
            localStorage.name=e.data.cxfullname;
            localStorage.userid=e.data.userid;
            localStorage.lastlogintime=e.data.cxlastlogintime;
            callback();
        });
    }else{

        PostUrl('/api/v2.Login/checklogin',{token:localStorage.token},function(e){
            if(e.codes==200){
                console.log('TOKEN验证通过');
                callback();
            }else{
                localStorage.clear();
                console.log('TOKEN不匹配，请重新登陆 ');
                location.href='/api/v2.Wechat/PublicGoWeChat?urls='+location.href;
                return false;
            }

        })
    }
}


function CheckTokenPublic(callback){
    if(getQV('ok')){
        let  postD={
            openid:getQV('openid'),
            nickname:getQV('nickname'),
            headimgurl:getQV('headimgurl'),
        };
        PostUrl('/api/v2.Wechat/regUser',postD,function(e){
            console.log('登陆成功');
            localStorage.id=e.data.cxid;
            localStorage.username=e.data.cxusername;
            localStorage.token=e.data.cxtoken;
            localStorage.level=e.data.cxuserlevel;
            localStorage.img=e.data.cximg0;
            localStorage.name=e.data.cxfullname;
            localStorage.userid=e.data.userid;
            localStorage.lastlogintime=e.data.cxlastlogintime;
            callback();
        });
    }else {

        PostUrl('/api/v2.Login/checklogin', {token: localStorage.token}, function (e) {
            if (e.codes == 200) {
                console.log('TOKEN验证通过');
                callback();
            } else {
                localStorage.clear();
                console.log('TOKEN不匹配，请重新登陆 ');
                location.href = 'https://yewu.bcwhkj.cn/api/v2.Wechat/PublicGoWeChat?urls=' + location.href;
                return false;
            }

        });
    }

}

/**
 * @return kimi加密
 * @param strs 要加密的字符串
 */
function kimi(strs){
    if(strs){
        var encrypt = new JSEncrypt();
        //公钥
        encrypt.setPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2wBHOsFxwrvCWqwofc4xpXInIM6eNBKQMTHPhd4J0Fr3HyAyiz70OKdgEGK4sszC06x+izUqYunQByKDCCSbGjC1KM2aocbyDcfbK3e6t//YQhe4aygXj+6as2HLbqKmzniR5bqGaVAM9RHgsuWchIBgNFq4ke/0hdsiW1BtO3QIDAQAB");
        return encrypt.encrypt(strs);
    }else{
        return '';
    }
}

/**
 * @return 清除HTML
 */
function filterHTMLTag(msgHtml){
    if(msgHtml){
        let msg = msgHtml.replace(/<\/?[^>]*>/g, ''); //去除HTML Tag
        msg = msg.replace(/[|]*\n/, '') //去除行尾空格
        msg = msg.replace(/&npsp;/ig, ''); //去掉npsp
        msg = msg.replace(/&nbsp;/ig, ''); //去掉npsp
        return msg;
    }
}



function getQV(variable)//获取get参数
{

    //获取get参数
    var getV;
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){
            getV=decodeURI(pair[1]);
            return decodeURI(pair[1]);
        }
    }
    return(false);
}
function getPage(variable)//获取get参数
{

    //获取get参数
    var getV;
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){
            getV=decodeURI(pair[1]);
            return decodeURI(pair[1]);
        }
    }
    if(!getV){
        if(location.hash.replace('#!page=', '')){
            getV=location.hash.replace('#!page=', '');
            return getV;
        }
    }
    return(false);
}

/**
 * @return 随机数
 * @param min 最小值
 * @param max 最大值
 */
function sjs(min, max){
    //生成随机数
    return Math.floor(Math.random() * (max - min) ) + min;
}
function DateAdd(interval,number,date){
    // date 可以是时间对象也可以是字符串，
    // 如果是后者，形式必须为: yyyy-mm-dd hh:mm:ss 其中分隔符不定。"2006年12月29日 16点01分23秒" 也是合法的
    //这个函数已经尽量模仿 vbscript 中的 dateadd 函数
    //三个参数，第一个是变化的时间间隔，可以是年、月、日、周、时、分、秒、毫秒(扩展)，
    //第三个参数可以是时间对象，也可以是字符串（形式必须为：2006-12-29 14:32:57 或 2006年12月29日 14点32分57秒），
    //函数的返回值是新的时间对象。
    number = parseInt(number);
    if (typeof(date)=="string"){
        date = date.split(/\D/);
        --date[1];
        eval("var date = new Date("+date.join(",")+")");
    }
    if (typeof(date)=="object"){
        var date = date
    }
    switch(interval){
        case "y": date.setFullYear(date.getFullYear()+number); break;
        case "m": date.setMonth(date.getMonth()+number); break;
        case "d": date.setDate(date.getDate()+number); break;
        case "w": date.setDate(date.getDate()+7*number); break;
        case "h": date.setHours(date.getHour()+number); break;
        case "n": date.setMinutes(date.getMinutes()+number); break;
        case "s": date.setSeconds(date.getSeconds()+number); break;
        case "l": date.setMilliseconds(date.getMilliseconds()+number); break;
    }
    return date;
}

function jAjax(urls, postData,callback) {

    $.ajax({
        url: 'https://apis.map.qq.com/ws/location/v1/ip?output=jsonp&key=MOKBZ-EZE6D-ITC4K-HVE23-ZF7SS-YLF3I',
        type: 'GET',
        dataType:'jsonp',
        success: function (data) {
            console.log('return ajax');
            callback(data);
        }
    });
}
/**
 * @return 上传文件
 */
function PostFileUrl(urls, postData,callback) {
    axios.post(urls, postData)
        .then(function (res) {
            let data = res.data;
            console.log('---------------------');
            console.log('PostUrl:'+urls);
            if(postData){
                console.log('有传内容上去');
            }
            console.log('PostReturn:');
            console.log(data);
            callback(data);

        })
        .catch(function (error) {
            console.log('---------------------');
            console.log('PostUrl:'+urls);
            if(postData){
                console.log('有传内容上去');
            }
            console.log(error);

        });
}

function PostUrl(urls, postData,callback) {
    // if(postData.token){
    //     postData.token=kimi(postData.token);
    // }

    axios.post(urls, postData)
        .then(function (res) {
            let data = res.data;
            console.log('--------------------');
            console.log('PostUrl:'+urls+',PostData ↓↓',postData,'Post[ '+urls+' ] Return ↓↓↓',data);
            callback(data);

        })
        .catch(function (error) {
            console.log('--------------------');
            console.log('PostUrl:'+urls);
            console.log('PostData:'+JSON.stringify(postData));
            console.log('Catch[ '+urls+' ] Return ↓↓↓ ');
            console.log('%c'+error,'background-color:#f00;padding:3px;color:#fff');
        });
}
function GetUrl(urls, callback) {
    console.log('GetUrl:'+urls);
    axios.get(urls)
        .then(function (res) {
            let data = res;
            console.log('Get[ '+urls+' ] Return ↓↓↓ ');
            console.log(data);
            callback(data);

        })
        .catch(function (error) {
            console.log('Get[ '+urls+' ] Return ↓↓↓ ');
            console.log(error);
        });
}

//$.post(urls,
//   {
//        data: postData
//    },
//    function (data, status) {
//       console.log('status:'+status);
//       callback( data);
//   });


function formatN(v,l,is45){
    //要格式化的数字，要保留的小数点后几位，是否要4舍5入
    if(v=='' || v==undefined){return 0; return false;}
    let zeroLen='0';
    for (i = 1; i < l; i++) {
        zeroLen=zeroLen+'0';
    }
    let vs;
    if(is45){
        vs=numeral(v).format('0.'+zeroLen);
        for (i = 1; i < l; i++) {
            if(_this.right(vs,1)=='0'){vs=_this.left(vs,vs.length-1);}
        }
    }else{
        vs=v.toString();
        if(vs.indexOf('.')>0){
            vs=vs.substr(0,vs.indexOf('.'))+'.'+vs.substr(vs.indexOf('.')+1,l);
        }
        vs=parseFloat(vs);
    }
    return vs;


}

function bcJiSuan(a,operation,b){
    //高精度数字函数

    if(a==0 && b==0){return 0;}
    //console.info('高精度数字计算:'+a+operation+b);
    let result;

    a = (a*10000).toFixed(2);
    b = (b*10000).toFixed(2);
    a=_this.formatN(a,0,false);
    b=_this.formatN(b,0,false);
    if(operation=='+'){
        result=(a+b)/10000;
    }
    if(operation=='-'){
        result=(a-b)/10000;
    }
    if(operation=='*'){
        result=(a*b)/100000000;
    }
    if(operation=='/'){
        result=(a/b)/100000000;
    }
    console.log((a/10000)+operation+(b/10000)+'计算结果 ：'+result);
    //result=_this.formatN(result,5,false);
    return result;
}


function left(mainStr,lngLen){
    if(lngLen>0){return mainStr.substring(0,lngLen)}
    else{return null}
}
function right(mainStr,lngLen){
    //alert(mainStr.length)
    if(mainStr.length-lngLen>=0&&mainStr.length>=0&&mainStr.length-lngLen<=mainStr.length){
        return mainStr.substring(mainStr.length-lngLen,mainStr.length)}
    else{return null}
}
function mid(mainStr,starnum,endnum){
    if(mainStr.length>=0){
        return mainStr.substr(starnum,endnum)
    }else{return null}
    //mainStr.length
}

//头像处理
function imgVal(e){
    let result;
    if(e){
        if(e.substr(0,4)=='http'){
            result=e;
        }
        if(e.substr(0,8)=='/public/'){
            result=e;
        }
        if(e.substr(0,8)=='uploads/'){
            result='/public/'+e;
        }
    }else{
        result='https://vkceyugu.cdn.bspapp.com/VKCEYUGU-908027cd-0849-4303-ae20-d3bed9830e3a/e007bff3-50f4-452a-81f6-f27c1b6cb439.jpg';

    }
    return result;
}